/**
  抽离项目中多次使用的重复函数
*/
import http from '@/service/http';

/**
 * 导出文件
 * @param url 导出的API路径
 * @param params 导出的参数
 */

export const exportFile = (url: string, params: object) => {
  return new Promise((resolve, reject) => {
    // 避免对象双向绑定
    params = JSON.parse(JSON.stringify(params));

    Object.assign(params, {
      responseType: 'blob', //下载文件需要在请求里添加responseType
      timeOut: 1200000,
    });
    http
      .post(url, params)
      .then((res) => {
        // 使用 URL.createObjectURL(new Blob([]))下载文件
        const csvData = new Blob([res.data], { type: res.contentType }),
          fileName = decodeURI(res.fileName || '');
        // for IE
        const nav = window.navigator as any;
        if (window.navigator && nav.msSaveOrOpenBlob) {
          nav.msSaveOrOpenBlob(csvData, fileName);
        } else {
          // for no IE
          const elink = document.createElement('a');
          elink.style.display = 'none';
          elink.download = fileName;
          elink.href = URL.createObjectURL(csvData);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href);
          document.body.removeChild(elink);
        }
        resolve(1);
      })
      .catch((e) => {
        reject(e);
      });
  });
};

// 函数防抖
export const debounce = (fn: any, wait?: number) => {
  let timeout: any = null;
  wait = wait || 800;
  return function () {
    // @ts-ignore
    const that = this;
    if (timeout !== null) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      fn.apply(that);
    }, wait);
  };
};
